package com.zeny.online.controller;


import com.zeny.online.common.ResponseResult;
import com.zeny.online.common.SearchFriendsStatusEnum;
import com.zeny.online.entity.Users;
import com.zeny.online.entity.bo.UserBO;
import com.zeny.online.entity.vo.UserVO;
import com.zeny.online.service.UsersService;
import com.zeny.online.util.FileUtil;
import com.zeny.online.util.QiniuUtils;
import com.zeny.online.util.RedisUtil;
import com.zeny.online.util.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author online
 */
@RestController
@RequestMapping("/online/users")
@Api(tags = "用户模块")
public class UsersController {

    //连续登陆失败五次后需要等待五分钟后才能登陆
    private static final String LOGIN_FAIL_TIMES = "login_fail_time_";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UsersService usersService;

    @PostMapping("/registOrLogin")
    @ApiOperation(value = "登录或注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "{\n" +
                    "\"username\":\"zeny\",\n" +
                    "\"password\": 123456\n" +
                    "}", required = true)
    })
    public synchronized ResponseResult registOrLogin(@RequestBody Users user) throws Exception {
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return ResponseResult.fail().message("用户名或者密码不能为空");
        }
        //1. 判断用户名是否为空, 如果存在就登录,如果不存在则注册
        Users usernameIsExist = usersService.findUserByUsername(user.getUsername());
        Users userResult = null;
        if (usernameIsExist != null) {
            //1.1 登录
            userResult = usersService.login(user);
            if (userResult == null) {
                //获取连续登陆失败次数
                Integer times = (Integer) redisUtil.get(LOGIN_FAIL_TIMES + usernameIsExist.getId());
                if (times == null) {
                    times = 1;
                    redisUtil.set(LOGIN_FAIL_TIMES + usernameIsExist.getId(), times, 60 * 5);
                } else {
                    if (times >= 5) {
                        redisUtil.set(LOGIN_FAIL_TIMES + usernameIsExist.getId(), 5, 60 * 5);
                        return ResponseResult.fail().message("5分钟后再重新登录");
                    }
                    redisUtil.incr(LOGIN_FAIL_TIMES + usernameIsExist.getId(), 1);
                }
                return ResponseResult.fail().message("密码不正确");
            } else {
                //账户密码验证成功, 但是出现连续5次登陆失败
                Integer times = (Integer) redisUtil.get(LOGIN_FAIL_TIMES + userResult.getId());
                if (times != null && times < 5) {
                    redisUtil.del(LOGIN_FAIL_TIMES + userResult.getId());
                }
                if (times != null && times >= 5) {
                    return ResponseResult.fail().message("5分钟后再重新登录");
                }
            }
        } else {
            //1.2 注册
            userResult = usersService.regist(user);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userResult, userVO);
        return ResponseResult.ok().data(userVO);
    }


    @ApiOperation(value = "图片上传")
    @PostMapping("/uploadFaceBase64")
    public ResponseResult upload(@RequestBody UserBO userBO) throws Exception {
        if (userBO == null
                || StringUtils.isBlank(userBO.getUserId())
                || StringUtils.isBlank(userBO.getFaceData())) {
            return ResponseResult.fail().message("上传失败");
        }
        String faceData = userBO.getFaceData();
        String userId = userBO.getUserId();
        byte[] faceBytes = FileUtil.base64ToFile(faceData);
        String fileName = userId + "_" + new SnowFlake(5, 5).nextId() + ".png";
        //上传到七牛云
        QiniuUtils.upload2Qiniu(faceBytes, fileName);
        //获取旧照片,扔进redis
        Users oldUser = usersService.getById(userId);
        redisUtil.sSet("clean_img", oldUser.getFaceImage());
        //更新到数据库
        Users user = new Users();
        user.setId(userId);
        user.setFaceImage(fileName);
        user.setFaceImageBig(fileName);
        usersService.updateById(user);
        //封装vo
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(oldUser, userVO);
        userVO.setFaceImage(fileName);
        userVO.setFaceImageBig(fileName);
        return ResponseResult.ok().data(userVO).message("上传成功");
    }

    @ApiOperation(value = "昵称修改")
    @PostMapping("/updateNickname")
    public ResponseResult updateNickname(@RequestBody UserBO userBO) {
        if (userBO == null
                || StringUtils.isBlank(userBO.getUserId())
                || StringUtils.isBlank(userBO.getNickname())) {
            return ResponseResult.fail().message("修改失败");
        }
        String userId = userBO.getUserId();
        String nickname = userBO.getNickname();
        if (nickname.length() > 10) {
            return ResponseResult.fail().message("请减少字段长度(<=10)");
        }
        Users users = new Users();
        users.setId(userId);
        users.setNickname(nickname);
        boolean success = usersService.updateById(users);
        Users result = usersService.getById(userId);
        return success ? ResponseResult.ok().data(result) : ResponseResult.fail().message("修改失败");
    }

    @PostMapping("/search")
    @ApiOperation(value = "搜索好友, 精确查找")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", example = "123456789", required = true),
            @ApiImplicitParam(name = "friendUsername", value = "friendUsername", example = "friendUsername", required = true),
    })
    public ResponseResult search(String userId, String friendUsername) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(friendUsername)) {
            return ResponseResult.fail().message("");
        }
        Integer status = usersService.searchFriend(userId, friendUsername);
        if (status.equals(SearchFriendsStatusEnum.SUCCESS.status)) {
            //查询成功
            Users friend = usersService.findUserByUsername(friendUsername);
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(friend, userVO);
            return ResponseResult.ok().data(userVO);
        } else {
            return ResponseResult.fail().message(SearchFriendsStatusEnum.getMsgByKey(status));
        }

    }

}

